public class ONEN_AccountMaintenance {
// Written by Evan Callahan, copyright (c) 2007 NPower Seattle
	  
	public static boolean firstRun = true;
	 
	// this function sets a primary contact for each account you pass in -- and fixes the primary
    public static void SetPrimaryContact(set<Id> acctIds) {
    	//SWA: added support for ignoring default account
    	//SWA: get default account id
		// new method to lookup individual acct id
		Id DefaultAccountId = ONEN_DefaultAccount.GetIndividualAccountId();		
		
	   	// don't allow recursion
	   	if (firstrun) {	   		
	    	firstRun = false; 
	
			// get the accounts in the set
			Account[] accts = [select id, primary_contact__c, primary_contact_title__c from account where id IN :acctIds];
	
			// get all the contacts for the accounts in the set
			//SWA: add criteria to ignore contacts in the default account
			//SWA: need to deal with large return sets. Will get soql return set limits at some point
			Contact[] cons = [select id, accountid, title from contact where accountid IN :acctIds and AccountId!=:DefaultAccountId order by accountid, createddate];
			Map<Id, Contact> cMap = new Map<Id, Contact>();
			cMap.PutAll(cons);			

			// loop through the contacts to assign one to each account
			Map<Id, Id> primaryMap = new Map<Id, Id>();
			for (integer i=0; i<cons.size(); i++) {
				if (!primaryMap.containsKey(cons[i].accountid)) {
					primaryMap.put(cons[i].accountid, cons[i].id);
				}
			}
			
			// create a list of accounts that need updates
			Account[] upAccts = new Account[]{};
			
			// loop through the accounts
			for (Account a : accts) {
				//SWA: ignore the default account
				if (a.Id!=DefaultAccountId) {
					Id pcid = a.primary_contact__c;
					String pct = a.primary_contact_title__c;
					
					// first, check to make sure the contact is in this account
				   	if (pcid != null) {
			   			if (cMap.containsKey(pcid) && cMap.get(pcid).AccountId==a.id) {
		   				} else {
							// not in the account, so clear the primary contact
							pcid = null;
				   		}
				   	}
				
					// now get a new contact if needed
				   	if (pcid == null) {
				   		if (primaryMap.containsKey(a.id)) {
				   			pcid = primaryMap.get(a.id);
				   		}
					}
					
		   			// set the title in case it has changed
				   	if (pcid == null) {
				   		pct = null;
				   	} else {
			   			pct = cMap.get(pcid).title;
				   	}
				   	
					// update the account if necessary
					if (pcid != a.primary_contact__c || pct != a.primary_contact_title__c) {
						upAccts.add(
							new Account (
								id = a.id,
								primary_contact__c = pcid,
								primary_contact_title__c = pct
							)
						);
					}
				}
			}
			// now do the update
			//system.debug('Updating ' + upAccts.size() + ' accounts.');
			if (!upAccts.isEmpty()) Update upAccts;
	   	}
	   	firstrun=true;
	}
}